<template>
  <SidebarLayout title="文档" logo-to="/apps" ref="sidebarLayoutRef">
    <template #sidebar>
      <Menu
        ref="sidebarRef"
        :spaces="spaces"
        :selected-space="selectedSpace"
        :current-space-id="currentSpaceId"
        :search-query="searchQuery"
        @space-select="handleSpaceSelect"
        @create-space="handleCreateSpace"
        @delete-space="handleDeleteSpace"
        @space-updated="handleSpaceUpdated"
        @create-document="handleCreateDocument"
        @search="handleSearch"
        @document-select="onDocumentSelect"
        @document-edit="onDocumentEdit"
        @document-delete="onDocumentDelete"
        @document-create="onDocumentCreate"
      />
    </template>

    <template #content>
      <!-- 文档Tab管理 -->
      <div class="doc-tabs-container" v-if="showDocTabs">
        <!-- Tab标签栏 -->
        <div class="doc-tab-bar" v-if="documentTabs.length > 1">
          <div class="tab-list">
            <div
                v-for="tab in documentTabs"
                :key="tab.id"
                class="tab-item"
                :class="{ 'tab-active': tab.id === currentDocumentId }"
                @click="switchToDocument(tab.id)"
            >
              <span class="tab-title">{{ tab.title }}</span>
              <button
                  class="tab-close"
                  @click.stop="closeDocumentTab(tab.id)"
                  v-if="documentTabs.length > 1"
              >
                ×
              </button>
            </div>
          </div>
        </div>

        <!-- Tab内容区域 -->
        <div class="doc-tab-content">
          <router-view/>
        </div>
      </div>

      <!-- 非文档页面直接显示 -->
      <router-view v-else/>
    </template>
  </SidebarLayout>
</template>

<script setup lang="ts">
import {ref, watch, computed, provide, onMounted} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import SidebarLayout from '@/components/SidebarMenu.vue'
import Menu from '../components/Menu.vue'
import type {Doc as DocumentType} from '@/modules/doc/types/doc.ts'
import type {NameSpace} from '@/modules/doc/types/namespace.ts'
import {useDocDetail, useDoc} from '@/modules/doc/composables'
import {namespaceApi} from '@/modules/doc/api'
import {toast} from '@/utils/message.ts'

const route = useRoute()
const router = useRouter()
const activeMenuId = ref('')

// 文档相关状态
const currentSpaceId = ref<string | null>(null)
const sidebarRef = ref()

// 空间管理状态
const spaces = ref<NameSpace[]>([])
const selectedSpace = ref<NameSpace | null>(null)
const loadingSpaces = ref(false)

// 搜索状态
const searchQuery = ref('')

// 使用composables
const {} = useDoc()

// Tab管理接口
interface DocumentTab {
  id: string
  title: string
  path: string
}

// Tab管理状态
const documentTabs = ref<DocumentTab[]>([])
const currentDocumentId = ref<string | null>(null)

// SidebarLayout 引用
const sidebarLayoutRef = ref()

const {fetchDocumentDetail} = useDocDetail()

// 空间管理方法
const loadSpaces = async () => {
  try {
    loadingSpaces.value = true
    const result = await namespaceApi.getAll()
    spaces.value = result

    // 如果有当前选中的空间ID，找到对应的空间对象
    if (currentSpaceId.value) {
      selectedSpace.value = spaces.value.find(space => space.id === currentSpaceId.value) || null
    }
  } catch (error) {
    console.error('加载空间列表失败:', error)
  } finally {
    loadingSpaces.value = false
  }
}

const handleSpaceSelect = (command: string) => {
  onSpaceSelect(command)
}

const handleCreateSpace = () => {
  // 可以在这里添加创建空间的逻辑，比如弹出创建对话框
  console.log('创建新空间')
}

const handleDeleteSpace = async (space: NameSpace) => {
  try {
    await namespaceApi.delete(space.id)
    toast.success('空间删除成功')
    
    // 如果删除的是当前选中的空间，清除选择
    if (selectedSpace.value?.id === space.id) {
      selectedSpace.value = null
      currentSpaceId.value = null
    }
    
    await loadSpaces()
  } catch (error) {
    toast.error('删除失败：' + (error as Error).message)
  }
}

const handleSpaceUpdated = async () => {
  // 空间更新后重新加载空间列表
  await loadSpaces()
}

const handleCreateDocument = () => {
  if (!currentSpaceId.value) {
    console.log('请先选择空间')
    return
  }

  // 调用创建文档逻辑
  onDocumentCreate(currentSpaceId.value)
}

const handleSearch = (_query: string) => {
  // 搜索逻辑由List组件处理，这里只需要更新searchQuery
  // List组件会通过props接收searchQuery并处理搜索
}

// 布局控制方法
const toggleSidebar = () => {
  if (sidebarLayoutRef.value) {
    sidebarLayoutRef.value.toggleSidebar()
  }
}

// 获取侧边栏显示状态
const showSidebar = computed(() => {
  return sidebarLayoutRef.value?.showSidebar ?? true
})

// Tab管理方法
const addOrSwitchToTab = async (docId: string, shouldNavigate: boolean = true) => {
  const existingTab = documentTabs.value.find(tab => tab.id === docId)

  if (existingTab) {
    // 如果tab已存在，切换到该tab
    currentDocumentId.value = docId
    if (shouldNavigate && route.params.id !== docId) {
      router.push(existingTab.path)
    }
  } else {
    // 创建新tab
    try {
      const document = await fetchDocumentDetail(docId, {
        showLoading: false,
        showError: false
      })

      if (document) {
        const newTab: DocumentTab = {
          id: docId,
          title: document.name,
          path: `/doc/${docId}`
        }
        documentTabs.value.push(newTab)
        currentDocumentId.value = docId
        if (shouldNavigate && route.params.id !== docId) {
          router.push(newTab.path)
        }
      }
    } catch (error) {
      console.error('获取文档详情失败:', error)
    }
  }
}

const switchToDocument = (docId: string) => {
  const tab = documentTabs.value.find(t => t.id === docId)
  if (tab) {
    currentDocumentId.value = docId
    router.push(tab.path)
  }
}

const closeDocumentTab = (docId: string) => {
  const tabIndex = documentTabs.value.findIndex(tab => tab.id === docId)
  if (tabIndex === -1) return

  // 移除tab
  documentTabs.value.splice(tabIndex, 1)

  // 如果关闭的是当前活跃tab
  if (currentDocumentId.value === docId) {
    if (documentTabs.value.length > 0) {
      // 切换到相邻tab
      const newActiveIndex = Math.min(tabIndex, documentTabs.value.length - 1)
      const newActiveTab = documentTabs.value[newActiveIndex]
      currentDocumentId.value = newActiveTab.id
      router.push(newActiveTab.path)
    } else {
      // 没有其他tab了，回到文档首页
      currentDocumentId.value = null
      router.push('/doc')
    }
  }
}

// 文档管理事件处理 - 通过事件总线或路由传递给main.vue
const onSpaceSelect = (spaceId: string) => {
  console.log('[index.vue] onSpaceSelect 被调用，空间ID:', spaceId)
  console.log('[index.vue] 当前 currentSpaceId:', currentSpaceId.value)

  if (currentSpaceId.value === spaceId) {
    console.log('[index.vue] 空间ID相同，跳过')
    return
  }

  currentSpaceId.value = spaceId
  // 更新选中的空间对象
  selectedSpace.value = spaces.value.find(space => space.id === spaceId) || null
  console.log('[index.vue] 已更新 currentSpaceId 为:', spaceId)

  // 触发路由变化，让main.vue重新加载文档
  if (route.path !== '/doc') {
    console.log('[index.vue] 导航到 /doc')
    router.push('/doc')
  }
}

const onDocumentCreate = (spaceId?: string) => {
  const targetSpaceId = spaceId || currentSpaceId.value
  if (!targetSpaceId) {
    toast.error('请先选择空间')
    return
  }
  
  // 直接跳转到新建文档页面，传递空间ID作为查询参数
  router.push(`/doc/create?spaceId=${targetSpaceId}`)
}

const onDocumentSelect = (document: DocumentType | null) => {
  // 通过路由导航到选中的文档，并添加到tab
  if (document && document.id && document.id !== '-1') {
    addOrSwitchToTab(document.id)
  }
}

const onDocumentEdit = (document: DocumentType) => {
  router.push(`/doc/edit/${document.id}`)
}

const onDocumentDelete = (_id: string) => {
  // 文档删除后刷新列表
  if (sidebarRef.value && sidebarRef.value.refreshDocuments) {
    sidebarRef.value.refreshDocuments()
  }
}

// 移除未使用的showDocContent

// 控制是否显示文档tab
const showDocTabs = computed(() => {
  return route.path.startsWith('/doc') && route.params.id
})

// 移除未使用的handleMenuSelect

// 监听路由变化，更新当前激活的菜单
watch(
    () => route.path,
    (path) => {
      if (path === '/doc/favorites') {
        activeMenuId.value = '/doc/favorites'
      } else if (path.startsWith('/doc')) {
        activeMenuId.value = '/doc'
      }
    },
    {immediate: true}
)

// 监听路由参数变化，同步当前文档ID
watch(() => route.params.id, (newId) => {
  if (newId && typeof newId === 'string') {
    currentDocumentId.value = newId
    // 如果当前文档不在tabs中，自动添加（但不导航，避免干扰刷新）
    if (!documentTabs.value.find(tab => tab.id === newId)) {
      addOrSwitchToTab(newId, false)
    }
  }
}, {immediate: true})

// 组件挂载时加载空间列表
onMounted(() => {
  loadSpaces()
})

// 向子组件提供状态和方法
provide('currentSpaceId', currentSpaceId)
provide('onDocumentSelect', onDocumentSelect)
provide('onDocumentEdit', onDocumentEdit)
provide('onDocumentDelete', onDocumentDelete)
provide('toggleSidebar', toggleSidebar)
provide('showSidebar', showSidebar)
</script>

<style scoped>
/* 只保留 Tab 相关的样式，布局样式已移到 SidebarLayout 组件 */


/* Tab容器样式 */
.doc-tabs-container {
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

/* Tab标签栏样式 */
.doc-tab-bar {
  background: rgba(var(--color-bg-light), var(--opacity-main));
  border-bottom: 1px solid rgba(var(--color-border-light), var(--opacity-border-light));
  flex-shrink: 0;
  position: sticky;
  top: 0;
  z-index: 100;
  border-radius: 5px;
}

.tab-list {
  display: flex;
  overflow-x: auto;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.tab-list::-webkit-scrollbar {
  display: none;
}

.tab-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: transparent;
  border: none;
  border-bottom: 2px solid transparent;
  cursor: pointer;
  transition: all 0.2s ease;
  white-space: nowrap;
  min-width: 120px;
  max-width: 200px;
  position: relative;
}

.tab-item:hover {
  background: rgba(var(--color-bg-light), 0.6);
}

.tab-item.tab-active {
  background: rgba(var(--color-bg-light), var(--opacity-hover));
  border-bottom-color: #42b883;
}

.tab-title {
  flex: 1;
  font-size: 14px;
  color: #2c3e50;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.tab-active .tab-title {
  color: #42b883;
  font-weight: 500;
}

.tab-close {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 18px;
  height: 18px;
  background: transparent;
  border: none;
  border-radius: 50%;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: all 0.2s ease;
  flex-shrink: 0;
}

.tab-close:hover {
  background: #dee2e6;
  color: #333;
}

/* Tab内容区域 */
.doc-tab-content {
  flex: 1;
  overflow: visible;
}

/* 响应式适配已移到 SidebarLayout 组件 */

/* 深色模式Tab样式 */
.dark .doc-tab-bar {
  background: rgba(var(--color-bg-dark), var(--opacity-main));
  border-bottom-color: rgba(var(--color-border-dark), var(--opacity-border-dark));
}

.dark .tab-item {
  color: #e6e6e6;
}

.dark .tab-item:hover {
  background: rgba(var(--color-bg-dark), 0.6);
}

.dark .tab-item.tab-active {
  background: rgba(var(--color-bg-dark), var(--opacity-hover));
  border-bottom-color: #42b883;
}

.dark .tab-title {
  color: #e6e6e6;
}

.dark .tab-active .tab-title {
  color: #42b883;
}

.dark .tab-close {
  color: #b3b3b3;
}

.dark .tab-close:hover {
  background: #4a4a4a;
  color: #e6e6e6;
}

.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>